package com.example.game_app.adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.game_app.R;
import com.example.game_app.fragment.GameMatchViewFragment;
import com.example.game_app.util.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 定义菜单适配器和ViewHolder
 */
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
    private Context context;
    private ListView listView;
    private List<Map<String, String>> menuList;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    // 为设置选中的坐标颜色
    public static int selectedPosition = RecyclerView.NO_POSITION;

    // 将上下文和listview比赛列表id传递到构造函数中

    public MenuAdapter(Context context, ListView listview, List<Map<String, String>> menuList) {
        // 获取 游戏时间列表
        this.context = context;
        this.listView = listview;
        this.menuList = menuList;
    }

    @NonNull
    @Override
    public MenuAdapter.MenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item_layout, parent, false);
        return new MenuViewHolder(view);
    }

    /**
     * 在绑定数据到RecyclerView的ViewHolder时调用此方法。
     * 用于设置每个菜单项的显示状态，包括日期的显示和选中状态的视觉效果。
     *
     * @param holder   MenuAdapter的MenuViewHolder对象，用于持有和显示菜单项。
     * @param position 当前项的索引位置。
     */
    @SuppressLint("RecyclerView")
    @Override
    public void onBindViewHolder(@NonNull MenuAdapter.MenuViewHolder holder, int position) { // 适用RecyclerView
        // 从菜单列表中获取当前项的数据映射
        Map<String, String> map = menuList.get(position);
        String date = map.get("matchTime");
        date = date + "  |";
        holder.matchDate.setText(date);
        // 根据当前位置是否为选中状态，设置不同的视觉效果
        if (position == selectedPosition) {
            // 选中状态的背景色、文字颜色、文字大小和样式
            setActivityStyle(holder);
        } else {
            // 非选中状态的背景色、文字颜色、文字大小和样式
            setUnactuvityStyle(holder);

        }
        String finalDate1 = date;
        // 设置点击事件监听器
        holder.matchDate.setOnClickListener(v -> {
            // 根据所选日期查询当天的比赛
            getMatchByDate(finalDate1);
            // 如果当前位置已经被选中，不执行任何操作
            if (position == selectedPosition) return;
            // 如果之前有选中项，则刷新之前选中项的状态
            if (selectedPosition != RecyclerView.NO_POSITION) {
                notifyItemChanged(selectedPosition);
            }
            selectedPosition = position;
            // 设置样式
            setActivityStyle(holder);

        });
    }


    // 根据所选日期查询比赛并显示
    private void getMatchByDate(String date) {
        new Thread() {
            public void run() {
                String result = Request.post("/matches/date", "param=" + date);
                // 将 新数据 再次映射上去
                List<Map<String, String>> newMatchList;
                try {
                    // 解析数据
                    newMatchList = parseMatchData(result);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                // List<Map<String, String>> finalNewMatchList = newMatchList;
                // 更新数据集，并通知更新
                mHandler.post(() -> listView.setAdapter(new MatchListAdapter(context, newMatchList, map -> {
                    // 创建弹出框
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(listView.getContext());
                    TextView messageView = new TextView(listView.getContext());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        messageView.setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1);
                        messageView.setGravity(Gravity.CENTER_HORIZONTAL);
                    }
                    String message = "队伍1：" + map.get("playerA") + "\n" +
                            "队伍2：" + map.get("playerB") + "\n" +
                            "比分：" + map.get("score") + "\n" +
                            "比赛时间：" + map.get("matchTime") + "\n" +
                            "比赛介绍：" + map.get("matchDescription");
                    messageView.setText(message);
                    alertDialogBuilder.setView(messageView)
                            .setTitle("比赛详情")
                            .setPositiveButton("确定", null)
                            .create()
                            .show();
                })));
            }
        }.start();
    }

    // 解析数据
    private List<Map<String, String>> parseMatchData(String jsonData) throws JSONException {
        List<Map<String, String>> matchList = new ArrayList<>();
        JSONArray jsonArray = new JSONArray(jsonData);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String matchId = String.valueOf(jsonObject.getInt("matchId"));
            String playerA = jsonObject.getString("playerA");
            String playerB = jsonObject.getString("playerB");
            String matchTime = jsonObject.getString("matchTime");
            String score = jsonObject.getString("score");
            String matchDescription = jsonObject.getString("matchDescription");

            Map<String, String> matchMap = new HashMap<>();
            matchMap.put("matchId", matchId);
            matchMap.put("playerA", playerA);
            matchMap.put("playerB", playerB);
            matchMap.put("matchTime", matchTime.substring(11, 16));
            matchMap.put("score", score);
            matchMap.put("matchDescription", matchDescription);
            matchList.add(matchMap);
        }
        return matchList;
    }


    @Override
    public int getItemCount() {
        return menuList.size();
    }

    // 列表元素缓存
    static class MenuViewHolder extends RecyclerView.ViewHolder {
        TextView matchDate;

        public MenuViewHolder(@NonNull View itemView) {
            super(itemView);
            matchDate = itemView.findViewById(R.id.match_date);
        }
    }

    //   重置所有选中状态
    @SuppressLint("NotifyDataSetChanged")
    public void resetSelectPosition() {
        selectedPosition = RecyclerView.NO_POSITION;
        // 刷新适配器以清除所有项目的选中状态
        notifyDataSetChanged();
    }

    private void setUnactuvityStyle(@NonNull MenuViewHolder holder) {
        holder.matchDate.setBackgroundColor(context.getResources().getColor(R.color.white));
        holder.matchDate.setTextColor(context.getResources().getColor(R.color.black));
        holder.matchDate.setTextSize(20);
        holder.matchDate.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
    }

    private void setActivityStyle(@NonNull MenuViewHolder holder) {
        holder.matchDate.setBackgroundColor(context.getResources().getColor(R.color.dateActivityBackground));
        holder.matchDate.setTextColor(context.getResources().getColor(R.color.dateActivityTextColor));
        holder.matchDate.setTextSize(22);
        holder.matchDate.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    }
}
